from rest_framework.response import Response
from rest_framework.views import APIView

from .models import News, Advert
from .ser import NewsSer, AdvertSer


class NewAPIView(APIView):
    def post(self, request):
        data = NewsSer(data=request.data)
        if data.is_valid():
            data.save()
            return Response({'msg': '添加成功'})
        else:
            return Response({'msg': '添加失败'})

    def get(self, request):
        data = News.objects.all()
        ser = NewsSer(data,many=True)
        return Response(ser.data)


class AdvertAPIView(APIView):
    def post(self, request):
        data = AdvertSer(data=request.data)
        if data.is_valid():
            data.save()
            return Response({'msg': '添加成功'})
        else:
            return Response({'msg': '添加失败'})

    def get(self, request):
        data = Advert.objects.all()
        ser = AdvertSer(data, many=True)
        return Response(ser.data)
